package com.farm.iproject.service.impl;

import com.farm.iproject.domain.Appmodel;
import com.farm.iproject.domain.Field;
import com.farm.iproject.domain.Project;
import com.farm.core.time.TimeTool;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.search.SortField.Type;

import com.farm.iproject.dao.FieldDaoInter;
import com.farm.iproject.dao.ProjectDaoInter;
import com.farm.iproject.service.FieldServiceInter;
import com.farm.wsch.index.WschIndexServerInter.DefaultField;
import com.farm.wsch.index.WschIndexServerInter.FieldType;
import com.farm.wsch.index.pojo.IndexDocument;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DataQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：项目字段服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class FieldServiceImpl implements FieldServiceInter {
	@Resource
	private FieldDaoInter fieldDaoImpl;
	@Resource
	private ProjectDaoInter projectDaoImpl;
	private static final Logger log = Logger.getLogger(FieldServiceImpl.class);

	@Override
	@Transactional
	public Field insertFieldEntity(Field entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		// entity.setCusername(user.getName());
		// entity.setEuser(user.getId());
		// entity.setEusername(user.getName());
		// entity.setEtime(TimeTool.getTimeDate14());
		entity.setPstate("1");
		if (isKeyidRepeat(entity.getKeyid(), null, entity.getProjectid())) {
			throw new RuntimeException("the keyid is repeat!(" + entity.getKeyid() + ")");
		}
		return fieldDaoImpl.insertEntity(entity);
	}

	@Override
	@Transactional
	public Field editFieldEntity(Field entity, LoginUser user) {
		Field entity2 = fieldDaoImpl.getEntity(entity.getId());
		if (DefaultField.getDic().get(entity2.getKeyid()) != null) {
			throw new RuntimeException("该域为系统域不可删除!");
		}
		// entity2.setEuser(user.getId());
		// entity2.setEusername(user.getName());
		// entity2.setEtime(TimeTool.getTimeDate14());
		entity2.setStoreis(entity.getStoreis());
		entity2.setTexttype(entity.getTexttype());
		entity2.setMaxlenght(entity.getMaxlenght());
		entity2.setType(entity.getType());
		// entity2.setProjectid(entity.getProjectid());
		entity2.setKeyid(entity.getKeyid());
		entity2.setName(entity.getName());
		entity2.setSortable(entity.getSortable());
		entity2.setPcontent(entity.getPcontent());
		entity2.setSort(entity.getSort());
		entity2.setSearchtype(entity.getSearchtype());
		entity2.setBoost(entity.getBoost());
		// entity2.setPstate(entity.getPstate());
		// entity2.setCuser(entity.getCuser());
		// entity2.setCtime(entity.getCtime());
		// entity2.setId(entity.getId());
		if (isKeyidRepeat(entity.getKeyid(), entity.getId(), entity.getProjectid())) {
			throw new RuntimeException("the keyid is repeat!(" + entity.getKeyid() + ")");
		}
		fieldDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteFieldEntity(String id, LoginUser user) {
		Field field = fieldDaoImpl.getEntity(id);
		if (DefaultField.getDic().get(field.getKeyid()) != null) {
			//throw new RuntimeException("该域为系统域不可删除!");
			return;
		}
		fieldDaoImpl.deleteEntity(field);
	}

	@Override
	@Transactional
	public Field getFieldEntity(String id) {
		// TODO 自动生成代码,修改后请去除本注释
		if (id == null) {
			return null;
		}
		return fieldDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createFieldSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "WSCH_P_FIELD A LEFT JOIN WSCH_P_PROJECT B ON A.PROJECTID=B.ID",
				"A.ID AS ID,A.SORTABLE as SORTABLE,A.TEXTTYPE as TEXTTYPE,A.BOOST as BOOST,A.SEARCHTYPE as SEARCHTYPE,A.SORT AS SORT,B.NAME AS PROJECTNAME,A.STOREIS AS STOREIS,A.TYPE AS TYPE,A.PROJECTID AS PROJECTID,A.KEYID AS KEYID,A.NAME AS NAME,A.PCONTENT AS PCONTENT,A.PSTATE AS PSTATE");
		return dbQuery;
	}

	@Override
	@Transactional
	public int getFieldsNum(String projectid) {
		DBRuleList rules = DBRuleList.getInstance();
		rules.add(new DBRule("PROJECTID", projectid, "="));
		return fieldDaoImpl.countEntitys(rules.toList());
	}

	@Override
	@Transactional
	public boolean isKeyidRepeat(String keyid, String id, String projectid) {
		DBRuleList rules = DBRuleList.getInstance();
		rules.add(new DBRule("KEYID", keyid, "="));
		rules.add(new DBRule("PROJECTID", projectid, "="));
		if (StringUtils.isNotBlank(id)) {
			rules.add(new DBRule("ID", id, "!="));
		}
		return fieldDaoImpl.countEntitys(rules.toList()) > 0;
	}

	@Override
	@Transactional
	public List<Field> getFields(String projectid) {
		DBRuleList rules = DBRuleList.getInstance();
		rules.add(new DBRule("PROJECTID", projectid, "="));
		List<Field> list = fieldDaoImpl.selectEntitys(rules.toList());
		Collections.sort(list, new Comparator<Field>() {
			@Override
			public int compare(Field o1, Field o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return list;
	}

	@Override
	@Transactional
	public void initProjectFields(Project project, LoginUser user) {
		int n = 0;
		for (DefaultField field : DefaultField.getList()) {
			Field field1 = new Field();
			field1.setKeyid(field.getKey());
			field1.setName(field.getTitle());
			field1.setProjectid(project.getId());
			field1.setSort(++n);
			field1.setStoreis("1");
			field1.setSearchtype("0");
			field1.setSortable("0");
			field1.setTexttype("1");
			field1.setType(FieldType.StringField.getKey());
			insertFieldEntity(field1, user);
		}
	}

	@Override
	@Transactional
	public IndexDocument getIndexDocument(String projectid, String appkeyid, Map<String, Object> map) {
		List<Field> fields = getFields(projectid);
		IndexDocument doc = new IndexDocument();
		for (Field field : fields) {
			doc.addField(FieldType.getType(field.getType()), (String) map.get(field.getKeyid()), field.getKeyid(),
					field.getStoreis().equals("1"));
		}
		return doc;
	}

	@Override
	@Transactional
	public List<Field> getSearchField(String projectid) {
		List<Field> appmodels = fieldDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PROJECTID", projectid, "=")).add(new DBRule("SEARCHTYPE", "1", "=")).toList());
		Collections.sort(appmodels, new Comparator<Field>() {
			@Override
			public int compare(Field o1, Field o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return appmodels;
	}

	@Override
	@Transactional
	public List<String> formatSearchField(String projectid, String fieldkeyid) {
		if (StringUtils.isBlank(fieldkeyid)) {
			fieldkeyid = "ALL";
		}
		List<String> fields = new ArrayList<String>();
		List<Field> allField = getSearchField(projectid);

		if (allField.size() <= 0) {
			throw new RuntimeException(" the project search field not exist!");
		}

		if (fieldkeyid.equals("ALL")) {
			for (Field node : allField) {
				fields.add(node.getKeyid());
			}
		} else {
			for (Field node : allField) {
				if (fieldkeyid.equals(node.getKeyid())) {
					fields.add(node.getKeyid());
				}
			}
		}
		if (fields.size() <= 0) {
			throw new RuntimeException(" the fieldkeyid is not exist：" + fieldkeyid);
		}
		return fields;
	}

	@Override
	@Transactional
	public Map<String, Float> getProjectFieldBoost(String projectid, List<String> fieldKeys) {
		List<Field> allField = getSearchField(projectid);
		Set<String> fieldkeyset = new HashSet<>(fieldKeys);
		Map<String, Float> boosts = new HashMap<String, Float>();
		for (Field field : allField) {
			if (fieldkeyset.contains(field.getKeyid())) {
				Integer boost = field.getBoost();
				if (boost == null) {
					boost = 1;
				}
				boosts.put(field.getKeyid(), new Float(boost));
			}
		}
		return boosts;
	}

	@Override
	@Transactional
	public Map<String, Field> getProjectFields(String projectid) {
		List<Field> appmodels = fieldDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectid, "=")).toList());
		Map<String, Field> map = new HashMap<>();
		for (Field field : appmodels) {
			map.put(field.getKeyid(), field);
		}
		return map;
	}

	@Override
	@Transactional
	public List<Field> getSortField(String projectid) {
		List<Field> appmodels = fieldDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("PROJECTID", projectid, "=")).add(new DBRule("SORTABLE", "1", "=")).toList());
		Collections.sort(appmodels, new Comparator<Field>() {
			@Override
			public int compare(Field o1, Field o2) {
				return o1.getSort() - o2.getSort();
			}
		});
		return appmodels;
	}

	@Override
	@Transactional
	public Field getFieldEntity(String projectid, String key) {
		List<Field> appmodels = fieldDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("PROJECTID", projectid, "=")).toList());
		for (Field node : appmodels) {
			if (node.getKeyid().trim().equals(key.trim())) {
				return node;
			}
		}
		return null;
	}
}
